﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using gt.dotnetcore.webapi.extensions;
using gt.dotnetcore.webapi.extensions.ApiException;
using gt.ShortMessage.Models;
using gt.ShortMessage.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace gt.ShortMessage.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ShortMessageController : ApiControllerBase
    {
        private readonly IMessageSendValidator _validator;
        private readonly IActiveCodeService _activeCodeService;
        private readonly ITokenService _tokenService;
        private readonly IShortMessageService _shortMessageService;

        public ShortMessageController(IMessageSendValidator validator,
            IActiveCodeService activeCodeService,
            ITokenService tokenService,
            IShortMessageService shortMessageService)
        {
            _validator = validator;
            _activeCodeService = activeCodeService;
            _tokenService = tokenService;
            _shortMessageService = shortMessageService;
        }


        [Route("ping")]
        [HttpGet]
        public IActionResult Ping()
        {
            return Ok("ok");
        }
        /// <summary>
        /// 发送短信验证码
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [BusinessExceptionFilter]
        [Route("activecode")]
        [HttpPost]
        public IActionResult ActiveCode(SendActiveCodeRequest request)
        {
            if (request == null ||
                string.IsNullOrEmpty(request.Phone) ||
                string.IsNullOrEmpty(request.UniqueId) ||
                string.IsNullOrEmpty(request.BusinessId))
                return BadRequest();

            if (!_validator.Validate(request.Phone, request.UniqueId))
                return Error(-1, "手机号或设备号发送次数受限！");

            var activeCode = _activeCodeService.GenerateActiveCode(request.Phone, request.UniqueId, request.BusinessId);
            var token = _tokenService.CreateActiveCodeToken(activeCode);
            var result = _shortMessageService.SendActiveCode(activeCode.Code, activeCode.BusinessId);

            if (!result)
                return Error(-2, "短信发送失败，请重新尝试！");

            _validator.AfterSend(request.Phone, request.UniqueId);

            return Success(token);
        }

        /// <summary>
        /// 短信验证码验证
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("verifyActivecode")]
        [HttpPost]
        public IActionResult VerifyActiveCode(VerifyActiveCodeRequest request)
        {
            if (request == null
                || string.IsNullOrEmpty(request.Code)
                || string.IsNullOrEmpty(request.Token))
                return BadRequest();

            ActiveCode activeCode = null;

            if (!_tokenService.VerifyActiveCodeToken(request.Token, request.Code, ref activeCode))
                return Error(-5, "验证失败！");

            //返回验证成功的token,用于后续处理业务。token应有 可验签、防篡改、时效性特征。这里jwt比较适合
            var successToken = _tokenService.CreateVerifyResultToken(activeCode.Phone, activeCode.UniqueId);
            return Success(successToken);
        }

        /// <summary>
        /// 通过短信验证码验证结果，处理具体业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("dosomething")]
        [HttpPost]
        public IActionResult DoSomething(DoSomethingReqeust request)
        {
            if (request == null
                || string.IsNullOrEmpty(request.VerifyToken)
                || string.IsNullOrEmpty(request.Dothings))
                return BadRequest();

            bool verifyResult = _tokenService.VerifyVerifyResultToken(request.VerifyToken);
            if (verifyResult)
            {
                return Success("i have do something ok.");
            }
            else
            {
                return Error(-8, "verify failed.");
            }
        }
    }
}